﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Coldairarrow.Util.Helper;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class EC_SyncOrderInterfaceBusiness : ECInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption EC_Query { get; set; }

        //推送的数据列表
        List<EC_ReqDTO_SyncOrder.Biz_Content> Biz_ContentList { get; set; } = new List<EC_ReqDTO_SyncOrder.Biz_Content>();


        public EC_SyncOrderInterfaceBusiness()
        {
            this.InterfaceName = "易仓订单同步";
            //索引字段
            this.MapFields = GetMapField("EC_Sync");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            EC_Query = this.interfaceOption.Where(x => x.OperateType == "EC_Sync").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求前的事件
            this.BeforeNoQueryEvent += EC_SyncOrderInterfaceBusiness_BeforeNoQueryEvent;
            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;
            //执行非查询请求后的事件
            this.AfterNoQueryEvent += EC_SyncOrderInterfaceBusiness_AfterNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EC_SyncOrderInterfaceBusiness_BeforeNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //获取请求的参数
                string pairs_s = noQueryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
                JObject pairs_o = JObject.Parse(pairs_s);
                noQueryEventArgs.CustomData = pairs_o;
                //获取
                noQueryEventArgs.CustomData2 = noQueryEventArgs.APINodes.Where(x => x.TargetField == "app_key").First().SreachKey;

            }
            catch (Exception ex)
            {

            }
        }




        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="EC_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {

            //获取请求的数据
            EC_ReqDTO_SyncOrder data = new EC_ReqDTO_SyncOrder();
            data.timestamp = DateTime.Now.ToUnixTimeStampMillis();
            //data.biz_content = noQueryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
            data.biz_content = noQueryEventArgs.Data.ToJson();
            data.sign = "";
            //获取Sign
            noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, data);
            var reqData = JObject.Parse(noQueryEventArgs.reqData);
            //获取所有json节点的信息
            var nodes = noQueryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == EC_Query.Id);
            //需要将请求的数据拼接到url中，先转换成字典
            Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
            foreach (var item in nodes)
            {
                if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                {
                    reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                }
            }

            data.sign = GetMD5Sign(reqKeyValue, noQueryEventArgs.CustomData2.ToString());
            noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, data);


        }
        /// <summary>
        /// 执行非查询请求后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void EC_SyncOrderInterfaceBusiness_AfterNoQueryEvent(object sender, EC_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //将返回的结果转换成对象
                var res = JObject.Parse(noQueryEventArgs.Result_s);
                //请求的数据，主要为了获取请求的原平台单号
                var temp = (EC_ReqDTO_SyncOrder.Biz_Content)noQueryEventArgs.Data;
                //API请求是否成功
                if (res["code"].ToString() == "200")//成功将返回的单号更新到数据库表中
                {
                    //获取返回的新单号
                    var biz_content = JObject.Parse(res["biz_content"].ToString());
                    var resOrder = biz_content["data"]["order_code"].ToString();
                    noQueryEventArgs.Success = true;
                    SqlDb.ExecuteSql($"UPDATE SD_LX_AMZOrderDetail SET EC_Synchronize='{resOrder}' WHERE amazon_order_id = '{temp.order_details.First().platform_order_code}' AND seller_name = '{temp.order.site}' AND seller_sku = '{temp.order_details.First().product_sku}'");
                }
                else if (res["code"].ToString() == "300" && res.ToString().Contains("系统已存在"))//已同步的单更新已同步标志
                {
                    //已同步的单号不再同步
                    noQueryEventArgs.Success = true;
                    SqlDb.ExecuteSql($"UPDATE SD_LX_AMZOrderDetail SET EC_Synchronize='O' WHERE amazon_order_id = '{temp.order_details.First().platform_order_code}' AND seller_name = '{temp.order.site}' AND seller_sku = '{temp.order_details.First().product_sku}'");
                    //AddLog(SqlDb, $"同步单号:{temp.order.reference_no},店铺:{temp.order.site}", InterfaceName, "EC_Sync", res.ToString());
                }
                else if (res["code"].ToString() == "300")//其他记录信息
                {
                    noQueryEventArgs.Success = true;
                    AddLog(SqlDb, $"同步单号:{temp.order.reference_no},店铺:{temp.order.site}", InterfaceName, "EC_Sync", res.ToString());
                }
                else//错误信息直接报错处理
                {
                    noQueryEventArgs.Success = false;
                    AddLog(SqlDb, $"同步单号:{temp.order.reference_no},店铺:{temp.order.site}", InterfaceName, "EC_Sync", res.ToString());
                }
            }
            catch (Exception ex)
            {
                noQueryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", noQueryEventArgs.Result_s);
                Thread.Sleep(30000);
            }
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的参数
                string pairs_s = queryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
                JObject pairs_o = JObject.Parse(pairs_s);
                queryEventArgs.CustomData = pairs_o;
                //获取
                queryEventArgs.CustomData2 = queryEventArgs.APINodes.Where(x => x.TargetField == "app_key").First().SreachKey;
                //设置查询第几页
                queryEventArgs.Page.PageIndex = 1;
                //一页的数量
                queryEventArgs.Page.PageSize = pairs_o["page_size"].ToString().ToInt();
                //查询的总天数
                queryEventArgs.Page.Total = pairs_o["condition"]["platform_create_date_start"].ToString().ToInt();
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的数据
                EC_ReqDTO data = new EC_ReqDTO();
                data.timestamp = DateTime.Now.ToUnixTimeStampMillis();
                var par = (JObject)queryEventArgs.CustomData;
                par["page"] = queryEventArgs.Page.PageIndex;//第几页
                par["condition"]["platform_create_date_start"] = DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd") + " 00:00:00";//入库单开始日期,等于
                par["condition"]["platform_paid_date_end"] = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";//入库单截止日期,不等于
                data.biz_content = par.ToJson();
                data.sign = "";
                //获取Sign
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                var reqData = JObject.Parse(queryEventArgs.reqData);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == EC_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                    }
                }

                data.sign = GetMD5Sign(reqKeyValue, queryEventArgs.CustomData2.ToString());
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                Ec_OrderLIstDTO result = (Ec_OrderLIstDTO)JsonConvert.DeserializeObject<Ec_OrderLIstDTO>(queryEventArgs.ResultStr);
                if (result.message == "Success")
                {
                    Ec_OrderLIstDTO_Data DTO_data = (Ec_OrderLIstDTO_Data)JsonConvert.DeserializeObject<Ec_OrderLIstDTO_Data>(result.biz_content);
                    //查询数量小于单页最大数量,当日数据查询完成
                    if (DTO_data.data.Count < queryEventArgs.Page.PageSize)
                    {
                        //查询下一页
                        queryEventArgs.Page.Complete = true;
                    }
                    else
                    {
                        //继续查询下一页
                        queryEventArgs.Page.PageIndex++;
                    }
                    queryEventArgs.Rows = DTO_data.data;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                //Thread.Sleep(20000);
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()

        {
            try
            {
                //获取领星FBM订单列表
                string sqlStr_select = $@"SELECT * FROM V_LX_WW_AMZOrderDetail WHERE fulfillment_channel='MFN'  AND (EC_Synchronize IS NULL or EC_Synchronize='' )  AND CONVERT(decimal,quantity_ordered) >0 AND buyer_name !=''";
                List<AMZOrderDetail> orderList = this.SqlDb.GetListBySql<AMZOrderDetail>(sqlStr_select);
                //获取店铺
            //    OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
            //    OL_Shop.Filters.Add(
            //new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
            //    //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
            //    );
            //    List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
            //    shopList.ForEach(x =>
            //    {
            //        //平台
            //        List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
            //        if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform_ = table.IsNullOrEmpty() ? "" : table.First().sid;
            //    });
                //List<AMZOrderDetail> sOrderList = new List<AMZOrderDetail>();
                ////判断那些订单需要更新
                //foreach (var item1 in ec_OrderLIsts)
                //{
                //    List<DbParameter> param = new List<DbParameter>();
                //    param.Add(SqlStringHelper.CreateParameter("@amazon_order_id", item1.refrence_no));
                //    List<AMZOrderDetail> orderList = this.SqlDb.GetListBySql<AMZOrderDetail>(sqlStr_select, param);
                //    if (!orderList.IsNullOrEmpty() && orderList.Count > 0)
                //    {
                //        sOrderList.AddRange(orderList);
                //    }
                //}
                if (!orderList.IsNullOrEmpty() && orderList.Count > 0)
                {
                    //推送的数据列表
                    foreach (var item1 in orderList.GroupBy(x => x.amazon_order_id + x.seller_name))
                    {
                        var f = item1.First().DeepClone();
                        //单据头
                        EC_ReqDTO_SyncOrder.Biz_Content biz_Content = new EC_ReqDTO_SyncOrder.Biz_Content();
                        biz_Content.action_type = "ADD";
                        biz_Content.order.platform = "b2c";
                        biz_Content.order.order_type = "line";
                        biz_Content.order.reference_no = f.amazon_order_id;
                        //biz_Content.order.reference_no = "test3";

                        //var shop = shopList.Where(x => x.Name == f.seller_name);
                        if (f.seller_name.Contains("五川"))
                        {
                            biz_Content.order.user_account = "Amazon_WuChuan";
                        }
                        else if (f.seller_name.Contains("百川"))
                        {
                            biz_Content.order.user_account = "Amazon_BaiChuan";
                        }
                        else if (f.seller_name.Contains("一川"))
                        {
                            biz_Content.order.user_account = "Amazon_YiChuan";
                        }
                        else if (f.seller_name.Contains("海纳"))
                        {
                            biz_Content.order.user_account = "Amazon_Haina";
                        }
                        else if (f.seller_name.Contains("TECASA"))
                        {
                            biz_Content.order.user_account = "Amazon_Tecasa";
                        }
                        else
                        {
                            biz_Content.order.user_account = "AMASON";
                        }

                            //biz_Content.order.user_account = shop.IsNullOrEmpty() ? "AMASON" : shop.First().ID+ "_Amazon";
                        //biz_Content.order.user_account = "Amazon_WuChuan";
                        biz_Content.order.currency = f.currency;
                        biz_Content.order.buyer_id = f.buyer_name;
                        biz_Content.order.buyer_name = f.buyer_name;
                        biz_Content.order.site = f.seller_name;
                        //biz_Content.order.warehouse_id = "AMASON";
                        //biz_Content.order.shipping_method = "AMASON";
                        //biz_Content.order.shipping_method_platform = "AMASON";
                        biz_Content.order.date_create_platform = f.purchase_date_local_utc.IsNullOrEmpty() ? "" : f.purchase_date_local_utc.ToDateTime().AddHours(8).ToString("yyyy-MM-dd HH:mm:ss");
                        biz_Content.order.platform_paid_date = f.posted_date_utc.IsNullOrEmpty() ? "" : f.posted_date_utc.Replace("T", " ").Replace("Z", "").ToDateTime().AddHours(8).ToString("yyyy-MM-dd HH:mm:ss");
                        biz_Content.order.ship_fee = f.shipping_price_amount;
                        biz_Content.order.buyer_mail = f.buyer_email;
                        //biz_Content.order.order_desc = item2.seller_name;
                        //biz_Content.order.paypal_transaction_id = item2.seller_name;
                        //biz_Content.order.transaction_id = item2.seller_name;
                        biz_Content.order.order_status = "2";
                        biz_Content.order.discount = f.item_discount;
                        //biz_Content.order.discount_deduction_method = item2.seller_name;
                        biz_Content.order.payment_method = f.payment_method;
                        //biz_Content.order.custom_order_type_name = "0";
                        biz_Content.order.shipping_method_no = f.tracking_number;
                        //biz_Content.order.face_base64 = "0";
                        //biz_Content.order.face_type = "0";
                        biz_Content.order.subtotal = f.order_total_amount;
                        //biz_Content.order.finalvaluefee = "0";
                        biz_Content.order.platform_fee = "0";
                        biz_Content.order.other_fee = "0";
                        biz_Content.order.seller_rebate = "0";
                        biz_Content.order.platform_latest_ship_date = f.latest_ship_date.IsNullOrEmpty() ? "" : f.latest_ship_date.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");

                        //地址信息
                        biz_Content.order_address.name = f.name;
                        biz_Content.order_address.country_code = f.country;
                        biz_Content.order_address.city_name = f.city;
                        biz_Content.order_address.postal_code = f.postal_code;
                        biz_Content.order_address.line1 = f.address_line1;
                        biz_Content.order_address.line2 = f.address_line2;
                        biz_Content.order_address.line3 = f.address_line3;
                        biz_Content.order_address.district = f.district;
                        biz_Content.order_address.state = f.state_or_region;
                        biz_Content.order_address.doorplate = f.shipping_address;

                        //格式化电话号码
                        if (f.phone.StartsWith("+1") && f.phone.Contains("ext."))
                        {
                            var temp = f.phone.Substring(0, f.phone.IndexOf("ext."));
                            biz_Content.order_address.phone = temp.Replace("+1", "").Replace(" ", "");
                        }
                        else
                        {
                            biz_Content.order_address.phone = f.phone;
                        }



                        biz_Content.order_address.company = f.address;

                        //订单附件
                        biz_Content.order_attachment.type = "";
                        biz_Content.order_attachment.name = "";
                        biz_Content.order_attachment.content = "";


                        //订单明细
                        int c = 0;
                        foreach (var item2 in item1)
                        {
                            EC_ReqDTO_SyncOrder.Biz_Content.Order_Details details = new EC_ReqDTO_SyncOrder.Biz_Content.Order_Details();
                            biz_Content.order_details.Clear();

                            var row = biz_Content.DeepClone();
                            if (row.order.reference_no == "112-1802492-7286635")
                            {
                                var TET = "";
                            }
                            //如果有多条明细，需要将订单号加上编号区分
                            if (item1.Count() > 1)
                            {
                                c = c + 1;
                                if (c > 1) row.order.reference_no = f.amazon_order_id + "-" + c;
                                else row.order.reference_no = f.amazon_order_id;
                            }
                            details.product_sku = item2.seller_sku;
                            details.unit_price = item2.unit_price_amount;
                            details.product_sku_qty = item2.quantity_ordered.IsNullOrEmpty() ? 0 : item2.quantity_ordered.ToInt();
                            details.product_title = item2.title;
                            details.product_url = item2.asin_url;
                            //details.ref_item_id = item2.unit_price_amount;
                            //details.op_ref_tnx = item2.unit_price_amount;
                            //details.unit_final_value_fee = item2.unit_price_amount;
                            //details.unit_transaction_price = item2.unit_price_amount;
                            //details.unit_other_fee = item2.unit_price_amount;
                            //details.order_remark = item2.unit_price_amount;
                            details.platform_order_code = item2.amazon_order_id;
                            //details.ref_item_location = item2.amazon_order_id;
                            //details.action = item2.amazon_order_id;
                            //details.sub_trade_order_index = item2.amazon_order_id;
                            //details.properties = item2.amazon_order_id;
                            row.order_details.Add(details);
                            Biz_ContentList.Add(row);
                        }
                    }

                    await this.ExecuteNoQuery<EC_ReqDTO_SyncOrder.Biz_Content>(Biz_ContentList, this.EC_Query, SqlDb);
                }

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "EC_Sync", "");
            }
        }

        /// <summary>
        /// 获取MD5 sign
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <param name="app_key"></param>
        /// <param name="reqData"></param>
        /// <returns></returns>
        public string GetMD5Sign(Dictionary<string, object> reqKeyValue, string secret_Key)
        {

            reqKeyValue = reqKeyValue.OrderBy(x => x.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in reqKeyValue)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("&");
            }
            //移除左后一个&连接符号
            sb.Remove(sb.Length - 1, 1);
            sb.Append(secret_Key);
            //string sign = sb.ToString().Replace("\n", "").Replace("\r", "");
            string sign = sb.ToString();
            //MD5加密
            sign = sign.ToMD5String().ToLower();
            return sign;
        }








        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
